package com.liuwish.learn.juc;

import com.google.common.base.Preconditions;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;

/***
 * HttpClentUtil
 * 
 * @author wjl
 */
public class HttpClientUtil {

	private static final Logger log = LogManager.getLogger(HttpClientUtil.class);
	/**
	 *setConnectTimeout 设置连接超时时间，单位毫秒。 
	 */
	private static final int  SET_CONNECT_TIMEOUT = 30000;
	/***
	 * setSocketTimeout：请求获取数据的超时时间，单位毫秒
	 */
	private static final int  SET_SOCKET_TIMEOUT = 30000;
	
	public static String httpGet(String url) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			//Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			httpclient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			// 设置参数
			httpGet.setURI(new URI(httpGet.getURI().toString()));
			// 发送请求
			response = httpclient.execute(httpGet);
			// 获取返回数据
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取返回数据
				body = EntityUtils.toString(entity, Consts.UTF_8);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (URISyntaxException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
				
		}
		return body;
	}
	
	
	public static String httpGet(String url, List<NameValuePair> params) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			httpclient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
			// 发送请求
			response = httpclient.execute(httpGet);
			// 获取返回数据
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取返回数据
				body = EntityUtils.toString(entity, Consts.UTF_8);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (URISyntaxException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
				
		}
		return body;
	}
	
	
	public static String httpGet(String url, List<NameValuePair> params, String charset) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			httpclient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
			// 发送请求
			response = httpclient.execute(httpGet);
			// 获取返回数据
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取返回数据
				body = EntityUtils.toString(entity,charset);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (URISyntaxException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
				
		}
		return body;
	}

	public static String httpGet(String url, Header[] headers, List<NameValuePair> params) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:''");
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
			httpGet.setHeaders(headers);
			response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", new Object[]{Integer.valueOf(response.getStatusLine().getStatusCode())});
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(entity);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException var30) {
			log.error("Can't send httpGet... " + var30.getMessage(), var30);
		} catch (IOException var31) {
			log.error("Can't send httpGet... " + var31.getMessage(), var31);
		} catch (IllegalArgumentException var32) {
			log.error("Can't send httpGet... " + var32.getMessage(), var32);
		} catch (URISyntaxException var33) {
			log.error("Can't send httpGet... " + var33.getMessage(), var33);
		} finally {
			if(null != httpclient) {
				try {
					httpclient.close();
				} catch (IOException var29) {
					log.error("Can't send httpGet... " + var29.getMessage(), var29);
				}
			}
			if(null != response) {
				try {
					response.close();
				} catch (IOException var28) {
					log.error("Can't send httpGet... " + var28.getMessage(), var28);
				}
			}

		}
		return body;
	}

	public static String httpGet(String url, Header header, List<NameValuePair> params) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
			httpGet.setHeader(header);
			// 发送请求
			response = httpclient.execute(httpGet);
			// 获取返回数据
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取返回数据
				body = EntityUtils.toString(entity);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (URISyntaxException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} finally {
			if (null != httpclient) {
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpGet(String url, Header[] headers) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			// 设置参数
			httpGet.setURI(new URI(httpGet.getURI().toString()));
			httpGet.setHeaders(headers);
			// 发送请求
			response = httpclient.execute(httpGet);
			// 获取返回数据
			HttpEntity entity = response.getEntity();
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获取返回数据
				body = EntityUtils.toString(entity);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} catch (URISyntaxException e) {
			log.error("Can't send httpGet... " + e.getMessage(), e);
		} finally {
			if (null != httpclient) {
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send httpGet... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpPost(String url, Header header, List<NameValuePair> formparams) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length()>0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
			httppost.setEntity(entity);
			httppost.setHeader(header);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body= EntityUtils.toString(response.getEntity());
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}catch(IllegalArgumentException e){
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}finally {
			if (null != httpclient) {
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpPost(String url, Header[]  headers, List<NameValuePair> formparams) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length()>0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
			httppost.setEntity(entity);
			httppost.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body= EntityUtils.toString(response.getEntity());
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}catch(IllegalArgumentException e){
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}finally {
			if (null != httpclient) {
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpPost(String url, Header[] headers, String outStr) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			httppost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(outStr, Consts.UTF_8);
			httppost.setEntity(stringEntity);
			httppost.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
			}
			EntityUtils.consume(stringEntity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpPost(String url, String outStr) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			httppost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(outStr, Consts.UTF_8);
			httppost.setEntity(stringEntity);
			Header[] headers = new BasicHeader[] { new BasicHeader("Content-Type", "application/json") };
			httppost.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
			}
			EntityUtils.consume(stringEntity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
				
		}
		return body;
	}

	public static String httpPost(String url, List<NameValuePair> formparams) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			httppost.setConfig(requestConfig);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
			httppost.setEntity(entity);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

	public static String httpPut(String url, String outStr) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			HttpPut httpput = new HttpPut(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SET_CONNECT_TIMEOUT).setConnectTimeout(SET_SOCKET_TIMEOUT).build();
			httpput.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(outStr, Consts.UTF_8);
			httpput.setEntity(stringEntity);
			Header[] headers = new BasicHeader[] { new BasicHeader("Content-Type", "application/json") };
			httpput.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httpput);
			log.info("http statuscode {}", response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
			}
			EntityUtils.consume(stringEntity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} finally {
			if (null != response){
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			}
		}
		return body;
	}

}
